package com.java1412.controller.api;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.java1412.entity.AliPay;
import com.java1412.entity.PayInfo;
import com.java1412.entity.User;
import com.java1412.service.CartService;
import com.java1412.service.PayInfoService;
import com.java1412.utils.ConstantUtil;
import com.java1412.utils.ResponseUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付接口
 *
 * @author java1412
 * @since 2023-06-26 16:14:48
 */
@RestController
@RequestMapping("/alipay")
public class AliPayController {
    @Resource
    private PayInfoService payInfoService;

    @Resource
    private CartService cartService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/pay")
    public String pay(AliPay aliPay, HttpSession session) {
        // 从session获取用户信息
        User loginUser = (User) session.getAttribute(ConstantUtil.LOGIN_USER_KEY);
        Integer userId = loginUser.getId();
        // 将userId存进redis
        // String traceNo = UUID.randomUUID().toString();
        long traceNo = new Date().getTime(); // 获取时间戳
        stringRedisTemplate.opsForValue().set(traceNo + "", userId + "");
        AlipayTradePagePayResponse response;
        try {
            // 创建发起API调用
            // pay(String subject, String outTradeNo, String totalAmount, String returnUrl) throws Exception {
            response = Factory.Payment.Page().pay(
                    URLEncoder.encode(aliPay.getSubject(), "UTF-8"),
                    //aliPay.getTraceNo(),
                    traceNo + "",
                    aliPay.getTotalAmount() + "",
                    "");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return response.getBody();
    }

    // 支付成功的时回调，主要获取支付宝生成支付流水号
    // /alipay/notify——无法内网访问，必须要走公网，做内网穿透
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) throws Exception {
        // 判断交易的状态
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("================支付成功================");
            // 获取支付的一些其他的数据
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            // 遍历，将requestParams打包到params
            for (String name : requestParams.keySet()) {
                // 将参数名和参数值存进到params
                params.put(name, request.getParameter(name));
            }
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 如果验证通过，返回的是一个true
                System.out.println("交易名称:" + params.get("subject"));
                System.out.println("交易状态:" + params.get("trade_status"));
                System.out.println("支付宝交易凭证号:" + params.get("trade_no"));
                System.out.println("商户订单号:" + params.get("out_trade_no"));
                System.out.println("交易金额:" + params.get("total_amount"));
                System.out.println("买家在支付宝唯一的id:" + params.get("buyer_id"));
                System.out.println("买家付款时间:" + params.get("gmt_payment"));
                System.out.println("买家付款金额:" + params.get("buyer_pay_amount"));
            }
            // 将支付宝生成信息存到本地数据库
            PayInfo payInfo = new PayInfo();
            // 获取用户id
            String outTraceNo = params.get("out_trade_no");
            String userId = stringRedisTemplate.opsForValue().get(outTraceNo);
            payInfo.setUserId(Integer.parseInt(userId));
            // 设置订单号
            payInfo.setOrderNo(Long.parseLong(outTraceNo));
            // 设置平台
            payInfo.setPayPlatform(1);
            // 设置支付流水号
            String tradeNo = params.get("trade_no");
            payInfo.setPlatformNumber(tradeNo);
            // 设置支付状态
            payInfo.setPlatformStatus(params.get("trade_status"));
            ResponseUtil r = payInfoService.add(payInfo);
            System.out.println(r);
            // 可以删除redis中当前用户的id
            stringRedisTemplate.delete(outTraceNo);
//            stringRedisTemplate.opsForValue().set(outTraceNo, userId, 0L, TimeUnit.SECONDS);
            // 删除当前用户的购物车
            ResponseUtil r2 = cartService.deleteCartsByUserId(Integer.parseInt(userId));
            System.out.println(r2);
        }
        return "success";
    }

    // 支付宝支付成功回调自己的跳转到成功页面
//    @GetMapping("/notify")
//    public String payNotify() {
//        System.out.println("支付成功跳转");
//        return "pay-success";
//    }
}
